package com.huatai.user.config;

import com.huatai.common.util.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.util.List;

/**
 * @program: ht-system
 * @description: 资源服务配置
 * @author: songxiude
 * @create: 2023-02-15 14:30
 **/
@Configuration
@EnableResourceServer
public class ResourceConfigServer extends ResourceServerConfigurerAdapter {
	//密钥
	@Value("${jwt.config.key}")
	private String tokenKey;
	//资源id
	@Value("${jwt.config.resourceid}")
	public String resourceid;

	//白名单
	@Value("#{'${huatai.bmd.skip-url}'.split(',')}")
	private List<String> bmdList;



	@Autowired
	private TokenStore tokenStore;


	@Override
	public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
		resources.resourceId(resourceid)
			.tokenStore(tokenStore)
			.stateless(true);
	}
	/**
	 * 默认是InMemoryTokenStore
	 * 也可以采用JdbcTokenStore，JwtTokenStore。
	 * @return
	 */
	@Bean
	public TokenStore tokenStore(){
		return new JwtTokenStore(accessTokenConverter());
	}

	@Bean
	public JwtAccessTokenConverter accessTokenConverter() {
		JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
		converter.setSigningKey(tokenKey); //对称秘钥，资源服务器使用该秘钥来验证
		return converter;
	}


	@Override
	public void configure(HttpSecurity http) throws Exception {
		String[] authorities = bmdList.toArray(new String[bmdList.size()]);
//
		//上线时打开验证
		http
			.authorizeRequests()
			//放行部分
			.antMatchers(authorities)
			.permitAll()
			//其他验证
			.antMatchers("/**")
			.access("#oauth2.hasScope('all')")
			.and()
			.csrf()
			.disable()
			.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
		//测试先放开
//		http
//			.authorizeRequests()
//			//放行部分
//			.antMatchers("/**")
//			.permitAll()
//			//其他验证
//			//.antMatchers("/**").access("#oauth2.hasScope('all')")
//			.and().csrf().disable()
//			.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

	}
}
